<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;

/*
 * A simplified port to PHP 5.5.3 from BOTK Core package
 */
class SimpleTemplateEngine
{

    protected 
        $template = '',
        $openDelimiter = '{',
        $closeDelimiter = '}',
        $values = array();


    public function __construct($template='',$openDelimiter = '{', $closeDelimiter = '}')
    {
        $this->setTemplate($template);
        $this->openDelimiter  = $openDelimiter;
        $this->closeDelimiter = $closeDelimiter;
    }

 
    public static function factory($template='',$openDelimiter = '{', $closeDelimiter = '}')
    {
        return new static($template,$openDelimiter, $closeDelimiter);
    }
    
    
     public function setTemplate($string)
     {
         $this->template=$string;
         
         return $this;
     }
     

    /**
     * Sets one or more template variables.
     */
    public function setVars(array $values, $merge = TRUE)
    {
        if (!$merge || empty($this->values)) {
            $this->values = $values;
        } else {
            $this->values = array_merge($this->values, $values);
        }
        
        return $this;
    }
    

    /**
     * Add one template variables.
     */
    public function addVar($tag,$value)
    {
        return $this->setVars(array ( $tag => $value));
    }


    /**
     * Renders the template and returns the result. 
     *
     */
    public function render()
    {
        $keys = array();

        foreach ($this->values as $key => $value) {
            $keys[] = $this->openDelimiter . $key . $this->closeDelimiter;
        }

        return str_replace($keys, $this->values, $this->template);
    }
}
